<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 报价单
 *
 */
class XBjhead extends Backend
{
    /**
     * XBjhead模型对象
     * @var \app\admin\model\XBjhead
     */
    protected $model = null;
    protected $user=null;
    protected $quickSearchField = ['BJNO'];

    protected $defaultSortField = 'BJNO,desc';
    protected $noNeedLogin      = ['*'];

    protected $preExcludeFields = [''];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\XBjhead;
        $this->user =new Admin();
    }
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $gstype=$this->request->get('gstype');
        $wheres=[];
        if($gstype){
            if($gstype==1)$wheres['CORPTYPE']='客户';
            else $wheres['CORPTYPE']='供应商';
        }
        $status='';
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        foreach ($where as $k=>$item) {
            if(in_array('x_bjhead.status',$item)){
                $status=" dbo.f_getflowstatus(BJNO) = '$item[2]'";
                unset($where[$k]);
            }
        }
        $m='';
        $adminInfo          = $this->auth->getInfo();
        $sal='';
        if($adminInfo['id']!=1){
            $sal="x_bjhead.SALES= '$adminInfo[nickname]'";
        }
        if(empty($where)){
            $m="dbo.f_getflowstatus(BJNO) != '已完成'";
        }
        $res = $this->model
            ->field(['x_bjhead.*,dbo.f_getflowstatus(BJNO) as status,codelib.codename'])
//            ->field(['*'])
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->join('codelib','x_bjhead.BJTYPE=codelib.code')
            ->alias($alias)
            ->where($status)
            ->where($where)
            ->where($wheres)
            ->where('codelib.CODETYPE','bjtype')
            ->where($m)
            ->where($sal)
            ->order($order)
//            ->fetchSql()->select();
            ->paginate($limit);
//var_dump($res);die;
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * @throws \think\db\exception\DbException
     * 审批列表页
     */
    public function index_s(){
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $get=$this->request->get();
        $wheres=[];
        if($get){
            if(isset($get['CORP']))  $wheres['CORP']=$get['CORP'];

        }
        $status='';
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        foreach ($where as $k=>$item) {
            if(in_array('x_bjhead.status',$item)){
                $status=" dbo.f_getflowstatus(BJNO) = '$item[2]'";
                unset($where[$k]);
            }
        }
        $adminInfo          = $this->auth->getInfo();
//        $adminInfo['id']='10016';
        //默认条件
        if(empty($where)){
            $m="exists ( select * from u_flowdata where u_flowdata.bizno=x_bjhead.BJNO   and iscurrent=1 and username='$adminInfo[nickname]') ";
        }else{
            $m="exists ( select * from u_flowdata where u_flowdata.bizno=x_bjhead.BJNO     and username='$adminInfo[nickname]') ";
        }

        $res = $this->model
            ->field(['*,dbo.f_getflowstatus(BJNO) as status'])
//            ->field(['*'])
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($status)
            ->where($where)
            ->where($m)
            ->where($wheres)
            ->order($order)
            ->paginate($limit);
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 添加 gstype判断供应商还是客户
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            $adminInfo          = $this->auth->getInfo();
            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
                //判断供应商还是客户
                if($data['gstype']==1) {
                    $data['BJNO']=$this->getmaxno('BJ');
//                    $data['BJNO']=date('Y',time()).'YJ'.time();;
                    $data['CORPTYPE']='客户';
                    if($data['CONTRACTNO']!='临时业务') {
                        if (!isset($data['GOODSID']) || !isset($data['CORP'])) {
                            $this->error('公司简称和装载产品不能为空');
                        }
                    }
                }else{
                    $data['BJNO']=$this->getmaxno('YJ');
//                    $data['BJNO']=date('Y',time()).'YJ'.time();;
                    $data['CORPTYPE']='供应商';
                    if($data['CONTRACTNO']!='临时业务') {
                        if (!isset($data['CORP'])) {
                            $this->error('公司简称');
                        }
                    }
                }


            $data['OP']=$adminInfo['nickname'];
            $data['OPTIME']=date('Y-m-d H:i:s',time());
            $data['SALES']=isset($data['SALES'])?$data['SALES']:$adminInfo['nickname'];
            $data['BJSTATUS']=0;
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                if(isset($data['CZY'])) {
                    $czy = [];
                    $adminInfo          = $this->auth->getInfo();
                    foreach ($data['CZY'] as $k => $item) {
                        $czy[$k] = ['BJNO' => $data['BJNO'], 'CZY' => $item, 'OP' => $adminInfo['nickname'], 'OPTIME' => date('Y-m-d', time())];
                    }
                    Db::table('x_bjheadczy')->insertAll($czy);
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'), $data['BJNO']);
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }
    /**
     * 编辑
     */
    public function edit()
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->field('*,dbo.f_getflowstatus(BJNO) as statuss')->with('czy')->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }
//        $czy=    Db::table('x_bjheadczy')->where('BJNO',$row->BJNO)->field('CZY')->select();
        $this->success('', [
            'row' => $row,
//            'status'=>   $this->status($row->BJNO),
//            'czy'=>$czy
        ]);
    }
    /**
     * 报价复制
     * @return mixed
     */
    public function copy(){
        $bjno=$this->request->get('bjno');
//        $bjno="2011BJ0001";
        $id          = $this->auth->getInfo()['id'];
        $sql="SET NOCOUNT ON ;DECLARE @BJNO VARCHAR(30) EXEC COPYBJ '$bjno','$id',@BJNO output select @BJNO as bjno";
        $status=Db::query($sql);
        $this->success('复制成功',$status[0]['bjno']);
    }

    /**
     * 报价提交审批
     */
    public function tj(){
        $post=$this->request->post('BJNO');
//        $post='2022BJ0001';
        //查询按钮状态
        $sql="select  dbo.f_getmetion_bjdtj('".$post."') as status";
        $status=Db::query($sql)[0]['status'];

        if($status==''){
            //查出报价人部门
            $head=$this->model->where('BJNO',$post)->value('SALES');
            $dep=$this->user->where('nickname',$head)->value('department');
            $s= $this->createflowdata($post,$dep,'报价审批',0);
            if($s==200){
                $this->success('提交成功');
            }else{
                $this->error('提交失败');
            }
        }else{
            $this->error($status);
        }
    }
    /**
     * 修改报价单状态
     */
    public function upstatus(){

        if ($this->request->isPost()) {
            $post=$this->request->post();
            //查询全部数据
            $data=$this->model->where('BJNO',$post['BJNO'])->find();
            if($post['BJSTATUS']==1){
                $sql="select  dbo.f_getmetion_bjdstatus('".$post['BJNO']."') as status";
                $status=Db::query($sql)[0]['status'];
                if($status!=''){
                    $this->error($status);
                }
                if($data['CORPTYPE']='供应商'){
                    if($data['CORP']==''){
                        $this->error('公司简称不能为空');
                    }
                }
            }


            $s= $this->model->where('BJNO',$post['BJNO'])->save(['ENDDATE'=>$post['ENDDATE'],'BJSTATUS'=>$post['BJSTATUS']]);
            if($s){
                $this->success('修改成功');
            }else{
                $this->error('修改失败');
            }
        }
        $get=$this->request->get('BJNO');
        $data=$this->model->where('BJNO',$get)->find();
        $this->success('',$data);
    }
    /**
     * 装载箱型
     */
    public function box (){
        $sql="select consize + contype  as box from container";
        $box=Db::query($sql);
        $this->success('',$box);
    }
    /**
     * 适装罐型
     */
    public function cantype (){
        $id=$this->request->get('id');
        $sql="select  dbo.f_getallowtanktype('".$id."') as type";
        $box=Db::query($sql);
        $type=explode('/',$box[0]['type']);
        $this->success('', [
            'list'   => $type,
            'total'  => count($type),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 查询报价人信息
     */
    public function getbj(){
        $get=$this->request->get('name');
       $data= Db::table('admin')->field('admin.mobile,admin.email,d.TELEPHONE,d.FAX')->join('DEPARTMENT d','admin.department=d.DEPTID')->where('admin.nickname',$get)->find();
        $this->success('',$data);
    }

}